package com.ninjia.api.filter;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebFilter(filterName = "accessLog", urlPatterns = "/*")
public class Logfilter implements Filter {
    public static Logger log = LoggerFactory.getLogger(Logfilter.class);

    @Override
    public void destroy() {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long startTime = System.currentTimeMillis();
        ResponseWrapper wrapper = new ResponseWrapper((HttpServletResponse) response);
        HttpServletRequest req = (HttpServletRequest) request;
        chain.doFilter(request, wrapper);
        long endTime = System.currentTimeMillis();
        Gson gson = new Gson();
        // 获取response返回的内容并重新写入response
        String result = wrapper.getResponseData(response.getCharacterEncoding());
        response.getOutputStream().write(result.getBytes());
        String uri = req.getRequestURI();
        log.info("URI:"+uri);
        log.info("Method:"+req.getMethod());
        log.info("Param:"+gson.toJson(req.getParameterMap()));
        log.info("Status:" + String.valueOf(wrapper.getStatus()));
        log.info("Return:"+ result);
        log.info("RequestTime:"+ new Date().toString());
        log.info("Times:"+String.valueOf(endTime - startTime)+"ms");
        /*AccessLog log =  new AccessLog();
        log.setMethod(req.getMethod());
        log.setUrl(uri);
        log.setParameters(gson.toJson(req.getParameterMap()));
        log.setResponseCode(String.valueOf(wrapper.getStatus()));
        log.setResult(result);
        log.setCreateDatetime(new Date());
        log.setTimeConsuming((int)(endTime - startTime));
        accessLogMapper.insertSelective(log);*/
    }
    @Override
    public void init(FilterConfig fConfig) throws ServletException {

    }
}
